import { Verify } from 'src/app/service/verify.service';
import { LocalStorage } from './../../service/localStorage.service';
import { ChangeDetectorRef, Component, OnInit } from '@angular/core';
import { CustomerServiceSvr } from 'src/app/service/register.service';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzUploadChangeParam, NzUploadFile } from 'ng-zorro-antd/upload';
import { CommonServiceSvr } from 'src/app/service/common.service';
import { Message } from '@angular/compiler/src/i18n/i18n_ast';
import { ResponseError } from 'pengesoft-ng-lib';
@Component({
  selector: 'app-personal-data',
  templateUrl: './personal-data.component.html',
  styleUrls: ['./personal-data.component.less']
})
export class PersonalDataComponent implements OnInit {

  constructor(public loginUser: CustomerServiceSvr,
    private msg: NzMessageService,
    private commonService: CommonServiceSvr,
    private local: LocalStorage,
    private message: NzMessageService,
    private changeDetectorRef: ChangeDetectorRef,
    private verify: Verify
  ) {
  }

  ngOnInit(): void {
    this.getUserData()
  }

  token: string = JSON.parse(localStorage.getItem('Token')!)
  customerId: string = JSON.parse(localStorage.getItem('customerId')!)
  isVisibleMiddle = false
  // 当前登录用户的信息
  currentUser = {
    Id: '',
    Name: '张三',
    Sex: 1,
    Birthday: new Date('2000-02-15'),
    NickName: '小兔子',
    Phone: '15602561892',
    Email: 'fox@qq.com',
    Password: '123456',
    Address: '成都市锦城区',
    State: 1,
    Avatar: '//zos.alipayobjects.com/rmsportal/ODTLcjxAfvqbxHnVXCYX.png',
    IdCard: '510953200005268562',
    Authentication: 1, // 身份认证
    VipId: '1562035',
    Credit: 0, // 信用分
    Integral: 10, // 积分
    CreateTime: new Date('2020-02-15'),
    UpdateTime: new Date('2022-02-15')
  }

  // 隐藏边框
  borderDisplay = true
  // 是否显示边框的控制
  borderStyle = true
  // 禁用按钮
  btnDisable = false
  // 是否认证
  Authentication: boolean = false
  idCard: string = ''
  name: string = ''
  birthday: string = ''


  // 上传图片
  beforeUpload = (file: NzUploadFile): boolean => {
    this.loginUser.updateCustomerAvatar(this.token, this.customerId, file as unknown as File).then(res=>{
      this.currentUser.Avatar = res
    })
    this.message.success('头像上传成功')
    return false;
  };


  // 身份认证弹框
  showModalMiddle() {
    this.isVisibleMiddle = true
  }

  // 弹框确认
  async handleOkMiddle() {
    if(this.verify.idCard(this.idCard)) {
      const res = await this.loginUser.updateAuthenticationInfo('', this.customerId, this.name, this.idCard)
      if (res === 1) {
        this.isVisibleMiddle = false;
        this.message.success('身份认证成功')
        this.getUserData()
      } else {
        this.isVisibleMiddle = true;
        this.message.error('身份认证失败，请重新认证')
      }
    }
  }

  // 弹框取消
  handleCancelMiddle(): void {
    this.isVisibleMiddle = false;
  }

  // 关闭窗口的回调
  handleClose(): void {
    this.name = ''
    this.idCard = ''
  }

  // 提交个人资料修改的表单数据
  async updateUserData() {
    if(this.verify.username(this.currentUser.NickName)&&this.verify.email(this.currentUser.Email)) {
      this.borderDisplay = true
      // console.log(this.currentUser.Birthday)
      const res = await this.loginUser.updateCustomer('', this.customerId, this.currentUser.Sex,
      Number(this.currentUser.Birthday), this.currentUser.NickName,this.currentUser.Email,
      this.currentUser.Address, this.currentUser.Avatar)
      this.getUserData()
      this.message.success('个人信息修改成功')
    }
  }

  // 取消修改
  cancelUpdate() {
    this.borderDisplay = true
    this.getUserData()
  }

  // 修改按钮
  prepareUpdate() {
    this.borderDisplay = false
  }

  // 身份证脱敏显示
  idDesensitization() {
    const temp = this.currentUser.IdCard.substring(3, 15)
    const newIdCard = this.currentUser.IdCard.replace(temp, '***********')
    return newIdCard
  }

  // 获取用户初始化信息
  async getUserData() {
    this.customerId = JSON.parse(localStorage.getItem('customerId')!)
    this.token = JSON.parse(localStorage.getItem('Token')!)
    const userData = await this.loginUser.getCustomerByPrimaryKey(this.token, this.customerId)
    this.currentUser = {...userData}
    this.birthday = this.formatTime(this.currentUser.Birthday)
    this.Authentication = this.currentUser.Authentication === 1 ? false: true
    console.log(userData)
    this.changeDetectorRef.markForCheck();
    this.changeDetectorRef.detectChanges();
  }

  // 格式化时间
  formatTime(time: string | number | Date) {
    time = new Date(time)
    let year = time.getFullYear()
    let month = time.getMonth() + 1
    let date = time.getDate()
    return year+'-'+month+'-'+date
  }

}
